package com.pansoft.openplanet.fragment;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.AlertDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.activity.AboutActivityNew;
import com.efounder.chat.activity.MultiLanguageActivity;
import com.efounder.chat.activity.MyUserInfoActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.RightTopMenuClickEvent;
import com.efounder.chat.model.LogoutEvent;
import com.efounder.chat.model.TabMenuClickEvent;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.StorageUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.EnergyQRCodeActivity;
import com.pansoft.openplanet.activity.EscrowAccountActivity;
import com.pansoft.openplanet.activity.IPComIntroActivity;
import com.pansoft.openplanet.activity.InviteFriendPosterActivity;
import com.pansoft.openplanet.activity.LuckMoneyPrepareActivity;
import com.pansoft.openplanet.activity.MyInviteCodeActivity;
import com.pansoft.openplanet.activity.SafetyArchitectureActivity;
import com.pansoft.openplanet.activity.StackActivity;
import com.pansoft.openplanet.activity.TradeLineActivity;
import com.pansoft.openplanet.activity.TransferActivity;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.WalletBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.PassWordAlertDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import pl.droidsonroids.gif.AnimationListener;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 我的界面
 */
public class TalkChainMyFragment extends BaseFragment implements OnClickListener {

    private static final String TAG = "TalkChainMyFragment";

    private StorageUtil storageUtil;
    private String avatar = "";
    private ImageView iv_avatar;
    private GifImageView ivCoin, ivCoinBack;
    private TextView tv_name;
    private TextView tv_fxid;
    private String fxid;
    private User user;
    private List<WalletBean> walleatBeanList = new ArrayList<>();
    private AccountDao accountDao;
    private SmartRefreshLayout refreshLayout;
    private boolean showLoading = true;
    private int friendAmount, tribeAmount;
    private TextView tvEnergyCoinAmount, tvFansAmount, tvFriendAmount, tvTribeAmount, tvAppsAmount,
            tvSilverDiamondAmount;
    private TextView tvTitle;
    private ImageView ivPlanet;
    private String planet = "";
    private TextView tvWalletAddress;
    private boolean isCoinClickable = true;
    private String filePath = "";
    private String inviteCode = "";
    private String userName = "";
    private String silverDiamond = "";
    private String pwr = "";
    private String address = "";
    private ScrollView scrollView1;
    ImageView ivRotateRight;
    ImageView ivRotateLeft;
    ObjectAnimator rightAnimation;
    ObjectAnimator leftAnimation;


//    private ScaleAnimation sato0 = new ScaleAnimation(1, 0, 1, 1,
//            Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_PARENT, 0.5f);
//
//    private ScaleAnimation sato1 = new ScaleAnimation(0, 1, 1, 1,
//            Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_PARENT, 0.5f);


//    public TalkChainMyFragment(StubObject stubObject) {
//        Bundle bundle = new Bundle();
//        bundle.putSerializable("stubObject", stubObject);
//        setArguments(bundle);
//    }

    public TalkChainMyFragment() {
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            refreshUser();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshUser();
        rightAnimation.resume();
        leftAnimation.resume();

    }

    private void refreshUser() {

        user = WeChatDBManager.getInstance().
                getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));

        tvTribeAmount.setText(WeChatDBManager.getInstance().getallGroupWithOutUsers().size() + "");
        //好友数量
        int friendCount = WeChatDBManager.getInstance().getallFriends().size();
        tvFriendAmount.setText(friendCount + "");
        int appsAmount = WeChatDBManager.getInstance().getallOfficialNumber().size();
        tvAppsAmount.setText(String.valueOf(appsAmount));


        if (user != null) {
            avatar = user.getAvatar();
            tv_name.setText(user.getNickName());
        }
        if (fxid != null && !fxid.equals("")) {
            tv_fxid.setText(fxid);
        } else {
            tv_fxid.setText(ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_not_set));
        }
        if (user != null) {
            tv_name.setText(user.getNickName());
        }
        LXGlideImageLoader.getInstance().showUserAvatar(getActivity(), iv_avatar, avatar);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (rightAnimation.isRunning()) {
            rightAnimation.pause();
        }
        if (leftAnimation.isRunning()) {
            leftAnimation.pause();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.talk_chain_fragment_my, null);
        accountDao = new AccountDao(getActivity());
        storageUtil = new StorageUtil(getActivity().getApplicationContext(), "storage");
        tvTitle = rootView.findViewById(R.id.tv_title);
        scrollView1 = (ScrollView) rootView.findViewById(R.id.scrollView1);

        RelativeLayout titleLayout = rootView.findViewById(R.id.title);
        //if (getString(R.string.special_appid).equals("StarAsset")) {
        if (getString(R.string.special_appid).equals("OSPOpenPlanet")) {
            //星际资产隐藏标题栏
            titleLayout.setVisibility(View.GONE);
        }

//        //当前账户
        showUser();
        initSwipeRefreshView(rootView);
        initUserView(rootView);
        initTopView(rootView);
        refreshUser();
        initBasePlanet();
        initBottomView(rootView);
        initRotateAnimation(rootView);
        initFlipAnimation();
        preLoadImage();

        getWallet();
        refreshLayout.autoRefresh();
        return rootView;
    }

    private void initBasePlanet() {
        String planetInChinese = "";
        planet = EnvironmentVariable.getProperty("tc_planet", "");
        switch (planet) {
            case "mercury":
                ivPlanet.setImageDrawable(getResources().getDrawable(R.drawable.mercury_bg));
                planetInChinese = ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_mercury);
                break;
            case "venus":
                ivPlanet.setImageDrawable(getResources().getDrawable(R.drawable.venus_bg));
                planetInChinese = ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_venus);
                break;
            case "earth":
                ivPlanet.setImageDrawable(getResources().getDrawable(R.drawable.earth_bg));
                planetInChinese = ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_earth);
                break;
            case "mars":
                ivPlanet.setImageDrawable(getResources().getDrawable(R.drawable.mars_bg));
                planetInChinese = ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_mars);
                break;
            case "jupiter":
                ivPlanet.setImageDrawable(getResources().getDrawable(R.drawable.jupiter_bg));
                planetInChinese = ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_jupiter);
                break;
            case "saturn":
                ivPlanet.setImageDrawable(getResources().getDrawable(R.drawable.saturn_bg));
                planetInChinese = ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_saturn);
                break;
            case "uranus":
                ivPlanet.setImageDrawable(getResources().getDrawable(R.drawable.uranus_bg));
                planetInChinese = ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_uranus);
                break;
            case "neptune":
                ivPlanet.setImageDrawable(getResources().getDrawable(R.drawable.neptune_bg));
                planetInChinese = ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_neptune);
                break;
            case "pluto":
                ivPlanet.setImageDrawable(getResources().getDrawable(R.drawable.pluto_bg));
                planetInChinese = ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_pluto);
                break;
            default:
                ivPlanet.setImageDrawable(getResources().getDrawable(R.drawable.base_bg3));
                planetInChinese = "";
                break;
        }
        tvTitle.setText(getResources().getString(R.string.base_planet, planetInChinese));
    }

    /**
     * 初始化下拉刷新
     */
    private void initSwipeRefreshView(View rootView) {
        refreshLayout = rootView.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                showLoading = false;
                initData();
            }
        });
    }

    /**
     * 初始化顶部用户界面
     */
    private void initUserView(View rootView) {
        fxid = String.valueOf(user.getId());//帐号
        avatar = user.getAvatar();
        iv_avatar = rootView.findViewById(R.id.iv_avatar);
        iv_avatar.setOnClickListener(this);
        tv_name = rootView.findViewById(R.id.tv_name);
        tv_name.setOnClickListener(this);
        tv_fxid = rootView.findViewById(R.id.tv_fxid);
        tv_fxid.setOnClickListener(this);
        TextView tvIdIntro = rootView.findViewById(R.id.tv_id_intro);
        tvIdIntro.setOnClickListener(this);
        tv_name.setText(user.getNickName());

    }

    /**
     * 初始化上半部分，好友、部落、能量币、地址、余额，转出等
     */
    private void initTopView(View rootView) {
        ivPlanet = rootView.findViewById(R.id.iv_rotate_right_ball);

        tvFriendAmount = rootView.findViewById(R.id.tv_friends_amount);
        tvFriendAmount.setOnClickListener(this);
        tvAppsAmount = rootView.findViewById(R.id.tv_apps_amount);
        tvFansAmount = rootView.findViewById(R.id.tv_fans_amount);
        tvTribeAmount = rootView.findViewById(R.id.tv_tribe_amount);
        tvTribeAmount.setOnClickListener(this);
        TextView tvTribe = rootView.findViewById(R.id.tv_tribe);
        tvTribe.setOnClickListener(this);
        TextView tvSell = rootView.findViewById(R.id.tv_sell);
        tvSell.setOnClickListener(this);
        TextView tvBuy = rootView.findViewById(R.id.tv_buy);
        tvBuy.setOnClickListener(this);

        tvWalletAddress = rootView.findViewById(R.id.tv_wallet_address);
        TextView tvAddressIntro = rootView.findViewById(R.id.tv_wallet_address_intro);
        tvWalletAddress.setOnClickListener(this);
        ImageView ivAddressCopy = rootView.findViewById(R.id.iv_copy_address);
        ivAddressCopy.setOnClickListener(this);
        tvEnergyCoinAmount = rootView.findViewById(R.id.tv_energy_coin_amount);
//        tvCnyAmount = rootView.findViewById(R.id.tv_cny);
        ivCoin = rootView.findViewById(R.id.iv_coin);
        ivCoin.setOnClickListener(this);
//        ivCoinBack = rootView.findViewById(R.id.iv_coin_back);
//        LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoin, R.drawable.coin_front);
//        ivCoinBack.setOnClickListener(this);
//        ivCoinBack.setVisibility(View.INVISIBLE);
        ivCoin.setVisibility(View.VISIBLE);
    }

    /**
     * 初始化下半部分，交易明细，银钻，黑钻，关于等
     */
    private void initBottomView(View rootView) {
        ImageView ivSilverDiamond = rootView.findViewById(R.id.iv_silver_diamond);
        ImageView ivBlackDiamond = rootView.findViewById(R.id.iv_black_diamond);
        LXGlideImageLoader.getInstance().displayImage(getActivity(), ivSilverDiamond, R.drawable.silver_diamond);
        LXGlideImageLoader.getInstance().displayImage(getActivity(), ivBlackDiamond, R.drawable.black_diamond);
        LinearLayout llAboutInfo = rootView.findViewById(R.id.about_info);
        llAboutInfo.setOnClickListener(this);
        LinearLayout llIntegralCard = rootView.findViewById(R.id.ll_integral_card);
        llIntegralCard.setOnClickListener(this);
        LinearLayout llSilverDiamond = rootView.findViewById(R.id.silver_diamond);
        llSilverDiamond.setOnClickListener(this);
        LinearLayout llBlackDiamond = rootView.findViewById(R.id.black_diamond);
        llBlackDiamond.setOnClickListener(this);
        LinearLayout llTradeDetail = rootView.findViewById(R.id.trade_detail);
        llTradeDetail.setOnClickListener(this);
        LinearLayout llInviteCode = rootView.findViewById(R.id.invite_code);
        llInviteCode.setOnClickListener(this);
        LinearLayout llSafetyArchitecture = rootView.findViewById(R.id.safety_architecture);
        llSafetyArchitecture.setOnClickListener(this);
        tvSilverDiamondAmount = rootView.findViewById(R.id.tv_points);
        LinearLayout llMyDevice = rootView.findViewById(R.id.ll_my_device);
        llMyDevice.setOnClickListener(this);
        LinearLayout llTuoguan = rootView.findViewById(R.id.ll_tuoguan);
        llTuoguan.setOnClickListener(this);
        LinearLayout llRedPackage = (LinearLayout) rootView.findViewById(R.id.ll_red_package);
        llRedPackage.setOnClickListener(this);
        //一键发币
        LinearLayout llOneClickSend = rootView.findViewById(R.id.ll_one_click_send);
        llOneClickSend.setOnClickListener(this);
        //邀请好友
        LinearLayout llMenuInvate = (LinearLayout) rootView.findViewById(R.id.ll_menu_invate);
        llMenuInvate.setOnClickListener(this);
        //多语言
//         LinearLayout llMultiLanguage = (LinearLayout) rootView.findViewById(R.id.ll_multi_language);
//         if(EnvSupportManager.isSupportMultiLanguage()){
//             llMultiLanguage.setVisibility(View.VISIBLE);
//         }else {
//             llMultiLanguage.setVisibility(View.GONE);
//         }
//        llMultiLanguage.setOnClickListener(this);

//         llTuoguan.setVisibility(View.GONE);
//        llRedPackage.setVisibility(View.GONE);
    }

    /**
     * 初始化顶部背景图的旋转动画
     */
    private void initRotateAnimation(View rootView) {

        //顶部转动动画
//        rotateRight = AnimationUtils.loadAnimation(getActivity(), R.anim.rotation_right);
//        rotateRight.setInterpolator(new LinearInterpolator());
//        rotateLeft = AnimationUtils.loadAnimation(getActivity(), R.anim.rotation_left);
//        rotateLeft.setInterpolator(new LinearInterpolator());

        ivRotateRight = rootView.findViewById(R.id.iv_rotate_right);
        ivRotateLeft = rootView.findViewById(R.id.iv_rotate_left);
        rightAnimation = ObjectAnimator.ofFloat(ivRotateRight, "rotation", 0f, 360f);
        rightAnimation.setDuration(240000);
        rightAnimation.setRepeatMode(ValueAnimator.RESTART);
        rightAnimation.setRepeatCount(ValueAnimator.INFINITE);
        rightAnimation.start();
        leftAnimation = ObjectAnimator.ofFloat(ivRotateLeft, "rotation", 360f, 0f);
        leftAnimation.setDuration(240000);
        leftAnimation.setRepeatMode(ValueAnimator.RESTART);
        leftAnimation.setRepeatCount(ValueAnimator.INFINITE);
        leftAnimation.start();
//        if (rotateRight != null) {
//            ivRotateRight.startAnimation(rotateRight);
//        }
//        if (rotateLeft != null) {
//            ivRotateLeft.startAnimation(rotateLeft);
//        }
    }

    /**
     * 初始化硬币翻转动画
     */
    private void initFlipAnimation() {
        //硬币翻转动画
//        sato0.setDuration(800);
//        sato1.setDuration(800);
//        sato0.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//
//            }
//
//            @Override
//            public void onAnimationEnd(Animation animation) {
//
//                if (ivCoin.getVisibility() == View.VISIBLE) {
//                    ivCoin.setAnimation(null);
//                    ivCoin.setVisibility(View.INVISIBLE);
//                    ivCoinBack.setVisibility(View.VISIBLE);
//                    ivCoinBack.startAnimation(sato1);
//                } else {
//                    ivCoinBack.setAnimation(null);
//                    ivCoinBack.setVisibility(View.INVISIBLE);
//                    ivCoin.setVisibility(View.VISIBLE);
//                    ivCoin.startAnimation(sato1);
//                }
//            }
//
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//
//            }
//        });
//
//        sato1.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//
//            }
//
//            @Override
//            public void onAnimationEnd(Animation animation) {
//                if (ivCoin.getVisibility() == View.VISIBLE) {
//                    LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoin, R.drawable.pwc_z);
//                } else {
//                    LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoinBack, R.drawable.pwc_f);
//                }
//            }
//
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//
//            }
//        });
    }

    /**
     * 加载数据
     */
    private void initData() {
        getUserInfo();

    }

    /**
     * 预加载图片，防止动画切换时闪一闪
     */
    private void preLoadImage() {
//        LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoin, R.drawable.coin_front_to_back);
//        LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoin, R.drawable.coin_back_to_front);
//        LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoin, R.drawable.coin_back);
//        LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoin, R.drawable.coin_front);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private void showUser() {

        user = WeChatDBManager.getInstance().
                getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
    }

    private void showPasswordDialog(final Intent intent) {
        PassWordAlertDialog dialog = new PassWordAlertDialog(getActivity(), new PassWordAlertDialog.OnEnterClick() {
            @Override
            public void passVerifySuccess(String passWord) {
                startActivity(intent);
            }
        });
        dialog.show();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EFHttpRequest.cancelRequest(TAG);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //TODO 处理tabmenu 点击(滚动到顶部)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void onSolveEvent(TabMenuClickEvent event) {
        if (getArguments() != null) {
            StubObject stubObject = (StubObject) getArguments().getSerializable("stubObject");
            if (event.isChildPage(stubObject) && !isHidden()) {
                scrollView1.fullScroll(ScrollView.FOCUS_UP);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.invite_code) {
            //跳转邀请码
            Intent intent = new Intent(getActivity(), MyInviteCodeActivity.class);
            intent.putExtra("inviteCode", inviteCode);
            intent.putExtra("userName", userName);
            startActivity(intent);
        } else if (id == R.id.tv_sell) {
            //转账界面
            Intent intent = new Intent(getActivity(), TransferActivity.class);
            intent.putExtra("myaddress", walleatBeanList.get(0).getAddress());
            intent.putExtra("balance", walleatBeanList.get(0).getBalance());
            intent.putExtra("filePath", walleatBeanList.get(0).getFilePath());
            startActivity(intent);
        } else if (id == R.id.tv_buy) {
            //转入界面
            Intent intent = new Intent(getActivity(), EnergyQRCodeActivity.class);
            startActivity(intent);
        } else if (id == R.id.iv_avatar || id == R.id.tv_name ||
                id == R.id.tv_fxid || id == R.id.tv_id_intro) {
            //我的个人信息
            Intent intent = new Intent(getActivity(), MyUserInfoActivity.class);
            intent.putExtra("id", user.getId());
            startActivity(intent);
        } else if (id == R.id.tv_tribe_amount || id == R.id.tv_tribe) {
            //群聊列表
//            Intent intent = new Intent(getActivity(), ChatRoomActivity.class);
//            startActivity(intent);
        } else if (id == R.id.about_info) {
            //关于界面
            Intent intent = new Intent(getActivity(), AboutActivityNew.class);
            startActivity(intent);
        } else if (id == R.id.ll_integral_card) {
            //关于积分卡
            StackActivity.start(getActivity());
        } else if (id == R.id.silver_diamond) {
            //积分记录界面
//            Intent intent = new Intent(getActivity(), PointsRecordActivity.class);
//            startActivity(intent);
        } else if (id == R.id.tv_wallet_address || id == R.id.iv_copy_address) {
            //复制账号
            ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
            // 将文本内容放到系统剪贴板里。
            cm.setText(walleatBeanList.get(0).getAddress());
            ToastUtils.setBgColor(getResources().getColor(R.color.black));
            ToastUtils.setMsgColor(getResources().getColor(R.color.op_text_white_color));
            ToastUtils.showShort(ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_base_id_copied));
        } else if (id == R.id.trade_detail) {
            //积分记录界面
//            Intent intent = new Intent(getActivity(), EmptyActivity.class);
//            startActivity(intent);
            if (walleatBeanList == null) {
                return;
            }
            if (walleatBeanList.size() == 0) {
                return;
            }
            TradeLineActivity.startTradeLineActivity
                    (getActivity(), IPAssetsConstant.CHAIN_ID_TURBOCHAIN, ResStringUtil.getString(R.string.open_planet_transfer_list), walleatBeanList.get(0).getAddress(),
                            "", walleatBeanList.get(0).getBalance(), null,
                            walleatBeanList.get(0).getFilePath(), 0);
        } else if (id == R.id.black_diamond) {
            //黑钻，加入IPCom矿池
            Intent intent = new Intent(getActivity(), IPComIntroActivity.class);
            startActivity(intent);
        } else if (id == R.id.iv_coin) {
            if (isCoinClickable) {
                isCoinClickable = false;
                //硬币正面翻转
//                Glide.with(getActivity()).load(R.drawable.coin_front_to_back).into(ivCoin);
//                LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoin, R.drawable.coin_front_to_back);
                try {
                    GifDrawable coinToBack = new GifDrawable(getResources(), R.drawable.me_energy_fronttoback);
                    coinToBack.setLoopCount(1);
                    final GifDrawable coinFront = new GifDrawable(getResources(), R.drawable.me_energy_front);

                    ivCoin.setImageDrawable(coinToBack);
                    coinToBack.addAnimationListener(new AnimationListener() {
                        @Override
                        public void onAnimationCompleted(int loopNumber) {
                            try {
                                GifDrawable coinBack = new GifDrawable(getResources(), R.drawable.me_energy_back);
                                coinBack.setLoopCount(1);
                                ivCoin.setImageDrawable(coinBack);
                                coinBack.addAnimationListener(new AnimationListener() {
                                    @Override
                                    public void onAnimationCompleted(int loopNumber) {
                                        try {
                                            final GifDrawable coinBackToFront = new GifDrawable(getResources(), R.drawable.me_energy_backtofront);
                                            coinBackToFront.setLoopCount(1);
                                            ivCoin.setImageDrawable(coinBackToFront);
                                            coinBackToFront.addAnimationListener(new AnimationListener() {
                                                @Override
                                                public void onAnimationCompleted(int loopNumber) {
                                                    ivCoin.setImageDrawable(coinFront);
                                                    isCoinClickable = true;
                                                }
                                            });
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            Log.e(TAG, "背面图");
////                        Glide.with(getActivity()).load(R.drawable.coin_back).into(ivCoin);
////                        LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoin, R.drawable.coin_back);
//
//                            ivCoin.setImageDrawable(coinBack);
//                            new Handler().postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    Log.e(TAG, "开始翻转");
////                                Glide.with(getActivity()).load(R.drawable.coin_back_to_front).into(ivCoin);
////                                LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoin, R.drawable.coin_back_to_front);
//                                    ivCoin.setImageDrawable(coinToBack);
//                                    new Handler().postDelayed(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            Log.e(TAG, "正面图");
////                                        Glide.with(getActivity()).load(R.drawable.coin_front).into(ivCoin);
////                                        LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoin, R.drawable.coin_front);
//                                            ivCoin.setImageDrawable(coinFront);
//                                            isCoinClickable = true;
//                                        }
//                                    }, coinBackToFront.getDuration());
//                                }
//                            }, 2000);
//                        }
//                    }, coinToBack.getDuration());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
//            LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoin, R.drawable.energy_coin);
//            LXGlideImageLoader.getInstance().displayImage(getActivity(), ivCoinBack, R.drawable.energy_coin_back);
//            ivCoin.startAnimation(sato0);
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    ivCoinBack.startAnimation(sato0);
//                }
//            }, 3000);

        } else if (id == R.id.safety_architecture) {
            //安全架构
            Intent intent = new Intent(getActivity(), SafetyArchitectureActivity.class);
            intent.putExtra("filePath", filePath);
            startActivity(intent);
        } else if (id == R.id.ll_my_device) {
            //我的设备
            try {
                Bundle bundle = new Bundle();
                bundle.putBoolean(EFTransformFragmentActivity.EXTRA_HIDE_TITLE_BAR, true);
                EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class.forName("com.efounder.chat.fragment.MultiLoginListFragment"), bundle);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else if (id == R.id.ll_tuoguan) {
            //托管账户
            EscrowAccountActivity.start(getActivity());
        } else if (id == R.id.ll_red_package) {
            //红包
            LuckMoneyPrepareActivity.start(getActivity());
//            LuckMoneyPosterActivity.start(getActivity(), "http://www.baidu.com", "PWR", "10000.12");

        } else if (id == R.id.ll_one_click_send) {
            //一键发币
            new AlertDialog.Builder(getActivity()).setTitle(ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_one_click_coin))
                    .setMessage(ResStringUtil.getString(R.string.open_planet_recharge_no_dredge))
                    .setCancelable(true)
                    .setPositiveButton(R.string.common_text_confirm, null).show();
        } else if (id == R.id.ll_menu_invate) {
            //邀请好友
            InviteFriendPosterActivity.start(getActivity());
        } else if (id == R.id.ll_multi_language) {
            MultiLanguageActivity.start(getActivity());
        }
    }

    private void getUserInfo() {
        HashMap<String, String> map = new HashMap<>();
        map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        TCRequestUtil.getOAuthRequest(TAG, "oauth/userInfo", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject userObject = new JSONObject(response);
                    if (userObject.has("userInfo")) {
                        JSONObject user = userObject.getJSONObject("userInfo");
                        tvFansAmount.setText(user.optInt("inviteCodeUseCount", 0) + "");
                        inviteCode = user.optString("inviteCode");
                        userName = user.optString("userName");
                        getBanlancefromServer();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_network_error));
                    // dismissLoading();
                    refreshLayout.finishRefresh();
                }
            }

            @Override
            public void onFail(String error) {
                refreshLayout.finishRefresh();
                //dismissLoading();
                if (error != null && error.equals("TokenExpireLogOut")) {
                    //showLogOutAlert();
                    EventBus.getDefault().post(new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE));
                    return;
                }
                ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_network_error));
            }
        });

    }

    //从服务器获取余额
    private void getBanlancefromServer() {

        if (walleatBeanList.size() == 0) {
            refreshLayout.finishRefresh();
            // dismissLoading();
            showLoading = true;
            //ToastUtil.showToast(getApplicationContext(), "请先添加新账户或者导入账户");
        } else {
            HashMap<String, String> map = new HashMap<>();
            map.put("ethAddress", walleatBeanList.get(0).getAddress());
            TCRequestUtil.postCommonRequest(TAG, "eth/ethGetBalance", map, new TCRequestUtil.TCRequestCallback() {
                @Override
                public void onSuccess(String response) {
                    JSONObject jsonObject = null;

                    try {
                        jsonObject = new JSONObject(response);
                        if (jsonObject != null && jsonObject.getString("result").equals("success")) {
                            String balance = jsonObject.getString("balance");
                            balance = BalanceUtil.balanceConvert(balance);
                            walleatBeanList.get(0).setBalance(balance);
                            if (balance.equals("0")) {
                                pwr = balance;
                                tvEnergyCoinAmount.setText(pwr);
                            } else {
                                pwr = BalanceUtil.formatPrice(Double.valueOf(balance), true, 8);
                                tvEnergyCoinAmount.setText(pwr);
                            }
//                            double cnyAmount = TCMathUtil.mul(Double.valueOf(balance), 100);
//                            tvCnyAmount.setText("￥ "+BalanceUtil.formatPrice(cnyAmount, true, 2));

                            refreshLayout.finishRefresh();
                            //dismissLoading();
                        }
                    } catch (Exception e) {
                        refreshLayout.finishRefresh();
                        e.printStackTrace();
                        // dismissLoading();
                    }
                }

                @Override
                public void onFail(String error) {
                    refreshLayout.finishRefresh();
                    //dismissLoading();
                    ToastUtils.setBgColor(getResources().getColor(R.color.black));
                    ToastUtils.setMsgColor(getResources().getColor(R.color.op_text_white_color));
                    ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                }
            });
        }
    }

//    private void dismissLoading() {
//        if (getActivity()!= null && !getActivity().isFinishing()) {
//            TCLoadingDataView.dismiss();
//        }
//    }

    @Override
    public void onDetach() {
        super.onDetach();
        LogUtils.e("onDetach");
    }

    //获取本地钱包地址
    private List<WalletBean> getWallet() {

        Account mainAccount = new AccountDao(getActivity()).getMainAccount();
        if (mainAccount == null) {
            mainAccount = accountDao.getAccount(EnvironmentVariable.getProperty("tc_ethAddress"));
            if (mainAccount != null) {
                mainAccount.setMaster(true);
                mainAccount.setEnable(true);
                mainAccount.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                accountDao.insertOrReplace(mainAccount);
            } else {
                return walleatBeanList;
            }
        }


        WalletBean walletBean = new WalletBean();
        walletBean.setAddress(mainAccount.getAddress());
        walletBean.setFile(new File(mainAccount.getFileName()));
        walletBean.setFilePath(mainAccount.getFileName());
        walletBean.setAccountName(mainAccount.getAcccountName());
        walletBean.setAvatar(mainAccount.getAccountAvatar());
        walleatBeanList.add(walletBean);
        address = walleatBeanList.get(0).getAddress();
        filePath = walleatBeanList.get(0).getFilePath();
        if (address.length() > 20) {
            address = address.replace(address.substring(6, address.length() - 4), "****");
            tvWalletAddress.setText(address);
            return walleatBeanList;
        } else {
            return walleatBeanList;
        }

    }

//    private android.support.v7.app.AlertDialog logOutDialog;
//
//    private void showLogOutAlert() {
//        if (logOutDialog != null && logOutDialog.isShowing()) {
//            logOutDialog.dismiss();
//        }
//        logOutDialog = new android.support.v7.app.AlertDialog.Builder(getActivity())
//                .setTitle("提示")
//                .setMessage("用户登录过期，请重新登录")
//                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        EventBus.getDefault().post(new LogoutEvent());
//                    }
//                })
//                .setCancelable(false)
//                .create();
//        logOutDialog.show();
//
//
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void rightTopMenuClickEvent(RightTopMenuClickEvent event) {
        StubObject stubObject = (StubObject) event.getStubObject();
        String id = stubObject.getObject("id", "").toString();
//        if (id.equals("open_planet_name")) {
//            StarAssetWalletPopup.showPopup(getActivity(), event.getView(), "");
//        }

    }
}
